import React, { useState, useEffect } from 'react'
import { Table, Form, Input, Button, Modal, message, PaginationProps, Pagination } from 'antd'
import { createNewNote, deleteNote, patchNote } from '@/util/request'
import { useAppDispatch, useAppSelector } from '@/store'
import { get_note_list_data_async } from '@/store/slice/note/request'
import { select_note_list_data, select_note_loading } from '@/store/slice/note/select'
import { set_note_list_data } from '@/store/slice/note'

interface Note {
  id: number
  title: string
  content: string
  _id: number
}

// 初始PAGE_SIZE的设置
let PAGE_SIZE = 6
// 总条数的显示
const showTotal: PaginationProps['showTotal'] = total => `总共有 ${total} 条笔记`
// 每页展示多少条数据
const pageSizeOptions = [6, 8, 10]

export default function MyNote() {
  // 存储笔记列表的状态
  const [notes, setNotes] = useState<Note[]>([])
  // 表单实例，用于管理表单数据
  const [form] = Form.useForm<Note>()
  // 控制模态框显示和隐藏的状态
  const [isModalVisible, setIsModalVisible] = useState(false)
  // 存储当前正在编辑的笔记的状态
  const [editingNote, setEditingNote] = useState<Note | null>(null)
  // 全局提示
  const [messageApi, contextHolder] = message.useMessage()
  // 表格是否可以被编辑
  const [componentDisabled, setComponentDisabled] = useState<boolean>(true)

  const dispatch = useAppDispatch()
  const noteListData = useAppSelector(select_note_list_data)
  const loading = useAppSelector(select_note_loading)

  useEffect(() => {
    dispatch(
      get_note_list_data_async({
        pageNo: 1,
        pageSize: PAGE_SIZE
      })
    )
  }, [])

  // 创建笔记
  const handleCreate = async () => {
    setComponentDisabled(false)
    form
      .validateFields()
      .then(async (values: any) => {
        const res = await createNewNote(values)
        if (res.data.code == 200) {
          messageApi.open({
            type: 'success',
            content: '新增笔记成功'
          })
          dispatch(
            get_note_list_data_async({
              pageNo: 1,
              pageSize: PAGE_SIZE
            })
          )
          form.resetFields()
          setIsModalVisible(false)
        } else {
          messageApi.open({
            type: 'error',
            content: '新增笔记失败'
          })
        }
      })
      .catch(err => {
        console.log(err)
      })
  }

  // 添加笔记
  const addNote = () => {
    setComponentDisabled(false)
    setIsModalVisible(true)
  }

  // 编辑笔记
  const handleEdit = (note: Note) => {
    setComponentDisabled(false)
    setEditingNote(note)
    form.setFieldsValue(note)
    setIsModalVisible(true)
  }

  // 查看笔记
  const handleSee = (note: Note) => {
    setComponentDisabled(true)
    setEditingNote(note)
    form.setFieldsValue(note)
    setIsModalVisible(true)
  }

  // 更新笔记的确认按钮
  const handleUpdate = async () => {
    if (editingNote) {
      const values = await form.validateFields()

      const res: any = await patchNote(editingNote.id, values)
      console.log(res)

      if (res.data.code == 200) {
        dispatch(
          get_note_list_data_async({
            pageNo: noteListData.current,
            pageSize: PAGE_SIZE
          })
        )
        messageApi.open({
          type: 'success',
          content: '修改笔记成功'
        })
        form.resetFields()
        setIsModalVisible(false)
        setEditingNote(null)
      } else {
        messageApi.open({
          type: 'error',
          content: '修改笔记失败'
        })
      }
    }
  }

  // 删除笔记
  const handleDelete = async (id: number) => {
    const res: any = await deleteNote(id)
    if (res.data.code == 200) {
      dispatch(
        get_note_list_data_async({
          pageNo: noteListData.current,
          pageSize: PAGE_SIZE
        })
      )
      messageApi.open({
        type: 'success',
        content: '删除笔记成功'
      })
    } else {
      messageApi.open({
        type: 'error',
        content: '删除笔记失败'
      })
    }
  }

  // 更改页数
  const changePage = (update_pageNo: number, update_pageSize: number) => {
    PAGE_SIZE = update_pageSize
    dispatch(
      get_note_list_data_async({
        pageNo: update_pageNo,
        pageSize: update_pageSize
      })
    )
    dispatch(set_note_list_data({ current: update_pageNo }))
  }

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 200
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content'
    },
    {
      title: '操作',
      key: 'action',
      width: 400,
      render: (_: any, record: Note) => (
        <div>
          <Button style={{ marginRight: '20px' }} type="primary" onClick={() => handleSee(record)}>
            查看
          </Button>
          <Button style={{ marginRight: '20px' }} type="primary" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="primary" danger onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </div>
      )
    }
  ]

  return (
    <>
      {contextHolder}
      <div>
        <Button type="primary" style={{ margin: '20px 0' }} onClick={() => addNote()}>
          添加笔记
        </Button>
        <Table dataSource={noteListData.list as any} columns={columns} rowKey="id" pagination={false} />
        <Pagination pageSize={PAGE_SIZE} onChange={changePage} current={noteListData.current} total={noteListData.count} pageSizeOptions={pageSizeOptions} showTotal={showTotal} showSizeChanger style={{ marginTop: 20 }} />
      </div>

      <Modal
        title={editingNote ? '编辑笔记' : '新增笔记'}
        visible={isModalVisible}
        onOk={editingNote ? handleUpdate : handleCreate}
        onCancel={() => {
          form.resetFields()
          setIsModalVisible(false)
          setEditingNote(null)
        }}
      >
        {/* Modal表单，用于输入笔记信息 */}
        <Form form={form} layout="vertical" disabled={componentDisabled}>
          <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入标题' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="content" label="内容" rules={[{ required: true, message: '请输入内容!' }]}>
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
